// 文件上传和下载

const express = require("express");
const multer = require("multer");
const path = require("path");

const router = express.Router();

// 设置存储配置
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/"); // 确保这个文件夹已经存在
  },
  filename: (req, file, cb) => {
    // 获取文件后缀
    const fileExtension = path.extname(file.originalname);
    const fileName = `file_${Date.now()}.${fileExtension}`;
    cb(null, fileName);
  },
});

const upload = multer({ storage: storage });

// 处理单个文件上传
router.post("/upload", upload.single("file"), (req, res) => {
  const file = req.file;
  if (!file) {
    return res.status(400).send("No file uploaded.");
  }
  res.send("File uploaded successfully.");
});

// 文件下载
router.get("/download", (req, res, next) => {
  try {
    // 获取文件路径
    const filePath = path.join(
      __dirname,
      "../../uploads/" + req.query.fileName
    );
    res.download(filePath);
  } catch (err) {
    next(err);
  }
});

module.exports = router;
